package com.jiu345.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * package:CustomFastJsonHttpMessageConverter
 *
 * @author MrLei QQ:235921049
 * desc:自定义过滤器,将Long类型雪花算法的ID转换成字符串格式传给前端
 * @Date 2024.07.14 8:41
 */
@Configuration
public class CustomFastJsonHttpMessageConverter {
    /**
     * 创建并配置 FastJsonHttpMessageConverter 的 Bean
     * @return 配置好的 HttpMessageConverters 对象
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 创建 FastJsonHttpMessageConverter 实例
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        // 创建 FastJson 配置对象
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        // 创建序列化特征列表
        List<SerializerFeature> list = new ArrayList<>();
        // 添加序列化特征，如美化格式、写入空值等
        list.add(SerializerFeature.PrettyFormat);
        list.add(SerializerFeature.WriteMapNullValue);
        list.add(SerializerFeature.WriteNullStringAsEmpty);
        list.add(SerializerFeature.WriteNullListAsEmpty);
        list.add(SerializerFeature.QuoteFieldNames);
        list.add(SerializerFeature.WriteDateUseDateFormat);
        list.add(SerializerFeature.DisableCircularReferenceDetect);
        list.add(SerializerFeature.WriteBigDecimalAsPlain);

        // 将列表转换为数组，并设置到 FastJson 配置中
        fastJsonConfig.setSerializerFeatures(list.toArray(new SerializerFeature[list.size()]));

        // 将 FastJson 配置设置到转换器中
        fastConverter.setFastJsonConfig(fastJsonConfig);

        // 创建转换器
        HttpMessageConverter<?> converter = fastConverter;

        // 添加自定义序列化过滤器
        fastJsonConfig.setSerializeFilters(new ValueFilter() {
            @Override
            public Object process(Object object, String name, Object value) {
                // 如果字段值是 Long 类型，并且字符串长度大于 15，则转换为 String 类型
                if (value != null && value.getClass() == Long.class) {
                    Long v = (Long) value;
                    if (v.toString().length() > 15) {
                        return String.valueOf(value);
                    }
                }
                // 否则返回原始值
                return value;
            }
        });

        // 创建并返回 HttpMessageConverters 对象
        return new HttpMessageConverters(converter);
    }
}
